package backTrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class P39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> collect = Arrays.stream(candidates).mapToObj(a -> (int) a).collect(Collectors.toList());
        Collections.sort(collect, (a, b) -> {
            return a - b;
        });
        List<List<Integer>> total = new ArrayList<>();
        backtrack(collect, 0, target, new ArrayList<>(), total);
        return total;
    }

    private void backtrack(List<Integer> candidates, int begin, int target, List<Integer> sub, List<List<Integer>> total) {
        if (target == 0) {
            total.add(new ArrayList(sub));
        } else if (target < candidates.get(0)) {
            return;
        } else {
            for (int i = begin; i < candidates.size(); i++) {
                int num = candidates.get(i);
                if (target < num) {
                    break;
                }
                // 添加当前数
                sub.add(num);
                backtrack(candidates, i, target - num, sub, total);
                sub.remove(sub.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> lists = new P39().combinationSum(new int[]{2, 3, 5}, 8);
        for (List<Integer> list : lists) {
            System.out.println(list);
        }
    }
}
